<?php

/**
 * Maikuro CMS
 *
 * LICENSE:
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * The license is bundled with this package in the file LICENSE.txt.
 * You may also obtain a copy of the License at this URL:
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @copyright  Copyright (c) 2010, Jonathan Hedrén
 * @author     Jonathan Hedrén <jonathan.hedren@gmail.com>
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 */

require_once 'entity/AdministratorEntity.php';
require_once 'entity/AdministratorPermissionEntity.php';

class AdministratorService extends AbstractDbEntityService
{
    protected $cacheIdentifier = 'administrator_cache',
              $dbTable         = 'administrator',
              $entityClass     = 'AdministratorEntity';

    /**
     * Creates an administrator permission entity.
     *
     * @param array $data
     * @return AdministratorPermissionEntity
     */
    public function createAdministratorPermission(array $data = null)
    {
        return $this->createEntity('AdministratorPermissionEntity', $data);
    }

    public function delete($idOrEntity) {
        $id = ($idOrEntity instanceof $this->entityClass) ? $idOrEntity->id : $idOrEntity;
        parent::delete($idOrEntity);
        $this->pdo->delete('administrator_permission', 'administratorId = ?', $id);
    }

    /**
     * Returns the user with the specified id.
     *
     * @param string $name
     * @return AdministratorEntity
     */
    public function getAdministrator($id)
    {
        return parent::get($id);
    }

    /**
     * Returns the user with the specified email.
     *
     * @param string $email
     * @return AdministratorEntity
     */
    public function getAdministratorByEmail($email)
    {
        foreach ($this->entities as $administrator) {
            if ($administrator->email == $email) {
                return $administrator;
            }
        }
        return null;
    }

    /**
     * Returns the user with the specified username.
     *
     * @param string $username
     * @return AdministratorEntity
     */
    public function getAdministratorByUsername($username)
    {
        foreach ($this->entities as $administrator) {
            if ($administrator->username == $username) {
                return $administrator;
            }
        }
        return null;
    }

    /**
     * Returns an array of all backend user entities.
     *
     * @return array
     */
    public function getAdministrators()
    {
        $administrators = array();
        foreach ($this->entities as $administrator) {
            $administrators[$administrator->id] = clone $administrator;
        }
        return $administrators;
    }

    /**
     * Fetches the administrators from the database.
     *
     * @return void
     */
    protected function fetchEntities()
    {
        parent::fetchEntities();

        foreach ($this->entities as $administrator) {

            $result = $this->pdo->select('ap.*', 'permission.subject', 'permission.type')
                                ->from('administrator_permission AS ap')
                                ->innerJoin('permission', 'ap.permissionId = permission.id')
                                ->where('administratorId = ?')
                                ->bindValues($administrator->id)
                                ->fetchAllAs('AdministratorPermissionEntity');
            if (count($result)) {
                foreach ($result as $permission) {
                    $id = '';
                    if ($permission->siteId != null) {
                        $id .= $permission->siteId . '/';
                    }
                    $id .= $permission->subject;

                    $administrator->permissions[$id] = $permission;
                }
            }
        }
    }

    /**
     *
     * @param AdministratorEntity $administrator
     * @return AdministratorEntity
     */
    public function save(AdministratorEntity $administrator)
    {
        if ($administrator->id != null && empty($administrator->password)) {

            // FIXME: Detta är

            $persistentAdministrator = $this->getAdministrator($administrator->id);
            $administrator->password = $persistentAdministrator->password;
        }

        parent::save($administrator);

        if ($administrator->id != null) {
            $this->pdo->delete('administrator_permission', 'administratorId = ?', $administrator->id);
        }
        
        foreach ($administrator->permissions as $permission) {
            $values = array(
                'administratorId' => $administrator->id,
                'permissionId' => $permission->permissionId,
                'siteId' => $permission->siteId,
                'accessLevel' => $permission->accessLevel
            );
            $this->pdo->insert('administrator_permission', $values);
        }

        return $administrator;
    }
}